<template>
    <ul class="list">
       <li class="item" v-for="item of letters" :key="item" @click="handleLetterClick" :ref="item"
       @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">{{item}}</li>
    </ul>
</template>

<script>
export default {
    name: 'CityAlphabet',
    props: {
        cities: Object
    },
    data () {
        return {
            touchStatus: false,//标识位，只有触发handleTouchStart之后才可以触发handleTouchMove
            startY: 0,
            timer: null
        }
    },
    updated () {
        this.startY=this.$refs['A'][0].offsetTop
    },
    computed: {
        letters () {//把这里Object类型的cities变成数组类型的letters，里面放的是ABCD....Z
            const letters=[]
            for(let i in this.cities){
                letters.push(i)
            }
            return letters
        }
    },
    methods: {
        handleLetterClick (el) {
            this.$emit("transmitLetter",el.target.innerHTML)   
        },
        handleTouchStart () {
            this.touchStatus=true
        },
        handleTouchMove (e) {//实现滚动字母表，列表相应滚动的功能
            if(this.touchStatus){
                //通过距离得出是哪个字母
                if(this.timer){
                    clearTimeout(this.timer)
                }
                this.timer=setTimeout(()=>{
                    //const startY=this.$refs['A'][0].offsetTop(优化了)//（第0项才是dom元素）获取字母表中A的距离顶部（和下文的页面最顶部不同，所以下文把距离减出来）的高度
                    const touchY=e.touches[0].clientY-79//touchmove事件自带的参数有一个touches的数组，第0项表示当前手指的信息,clientY表示距离页面最顶部的距离，-79是把header区减出来
                    const index=Math.floor((touchY-this.startY)/20)
                    if(index >= 0 && index < this.letters.length){
                        this.$emit('transmitLetter',this.letters[index])
                    }
                }, 10)
            }
        },
        handleTouchEnd () {
            this.touchStatus=false
        }
    }
}
</script>

<style lang="stylus" scoped>
    @import '~@/assets/styles/varibles.styl'
    .list
        position: absolute
        right: 0
        top: 1.58rem
        bottom: 0
        width: .4rem
        display: flex
        flex-direction: column
        justify-content: center
        .item
            text-align: center
            line-height: .4rem
            color: $bgColor
</style>
